<template>
  <div class="history-page">
    <!-- 页面头部：返回按钮 + 标题 -->
    <div class="page-header">
      <!-- 返回按钮 -->
      <button class="back-btn" @click="handleGoBack">
        < 返回
      </button>
      <!-- 原标题 -->
      <h1 class="page-title">历史记录</h1>
    </div>

    <div class="history-list">
      <!-- 年份分组循环 -->
      <div 
        v-for="(yearData, yearIndex) in historyData" 
        :key="yearIndex"
      >
        <HistoryRecordCard 
          v-for="(record, recordIndex) in yearData.records" 
          :key="recordIndex" 
          :year="recordIndex === 0 ? yearData.year : ''" 
          :orderId="record.startChargeSeq" 
          :cost="record.totalMoney" 
          :vin="record.vin" 
          :chargerId="record.connectorId" 
          :startTime="formatTime(record.startTime)" 
          :endTime="formatTime(record.endTime)" 
          :duration="formatDuration(record.chargeElapsedTime)" 
          :energy="record.totalPower" 
        />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import HistoryRecordCard from '@/components/HistoryRecordCard.vue'; 
import { getChargeRecord } from '@/api/api';

const router = useRouter();
const historyData = ref([]);
const emit = defineEmits(['backToMyPage']);

// 返回上一级
const handleGoBack = () => {
  emit('backToMyPage'); // 触发自定义事件
};

// 获取并处理数据
onMounted(async () => {
  try {
    const res = await getChargeRecord();
    if (res.code === 200 && res.data?.orderDetail) {
      const sortedRecords = [...res.data.orderDetail].sort((a, b) => {
        return new Date(b.endTime) - new Date(a.endTime);
      });

      const groupedData = {};
      sortedRecords.forEach((item) => {
        const year = new Date(item.endTime).getFullYear().toString();
        if (!groupedData[year]) {
          groupedData[year] = { year, records: [] };
        }
        groupedData[year].records.push(item);
      });

      historyData.value = Object.values(groupedData).sort((a, b) => {
        return parseInt(b.year) - parseInt(a.year);
      });
    }
  } catch (error) {
    console.error('获取充电记录失败：', error);
  }
});

// 格式化时间
const formatTime = (timeString) => {
  if (!timeString) return '';
  const date = new Date(timeString);
  if (isNaN(date.getTime())) return timeString;
  const month = date.getMonth() + 1;
  const day = date.getDate();
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');
  return `${month}月${day}日${hours}:${minutes}:${seconds}`;
};

// 格式化充电时长
const formatDuration = (minutes) => {
  return minutes + '分钟';
};
</script>

<style scoped>
.history-page {
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;
  background-color: #fff;
  min-height: 100vh;
  padding: 0 16px;
  font-size: 10px !important;
}

/* 页面头部布局 - 关键修改：让按钮左移 */
.page-header {
  padding: 12px 0;
  margin-bottom: 12px;
  display: flex;
  align-items: center;
  /* 移除了原有的margin-left，让按钮可以靠左显示 */
}

/* 返回按钮样式 */
.back-btn {
  background: transparent;
  border: none;
  color: #333;
  font-size: 16px !important;
  font-weight: 500;
  cursor: pointer;
  padding: 4px 8px;
  margin-right: 16px; /* 增加按钮与标题的间距 */
  /* 按钮左移的关键：可以根据需要调整这个值 */
}

.back-btn:hover {
  color: #007aff;
}

.page-title {
  font-size: 18px !important;
  font-weight: bold;
  color: #333;
  margin-left: 50px;
}

.history-list {
  display: flex;
  flex-direction: column;
  gap: 6px;
}

::v-deep .history-record-card {
  font-size: 8px !important;
}

::v-deep .history-record-card .record-field {
  font-size: 8px !important;
}
</style>
